package com.touchsun.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.touchsun.common.utils.PageUtils;
import com.touchsun.common.utils.Query;
import com.touchsun.product.dao.CategoryDao;
import com.touchsun.product.entity.CategoryEntity;
import com.touchsun.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 查询所有分类
        List<CategoryEntity> allData = baseMapper.selectList(null);
        // 构造分类
        return allData.stream()
                /*过滤出所有一级分类*/
                .filter(c -> {
                    return c.getParentCid().equals(0L);
                })
                /*查找一级分类的子分类*/
                .map(c -> {
                    // 递归查找
                    c.setChildren(this.getChildren(c, allData));
                    return c;
                })
                /*菜单排序, 根据sort字段*/
                .sorted(Comparator
                        .comparingInt(prev -> (prev.getSort() == null ? 0 : prev.getSort())))
                /*收集分类*/
                .collect(Collectors.toList());
    }

    /**
     * 查找当前菜单的子菜单
     * 递归
     * 
     * @param current 当前菜单
     * @param allData 所有数据
     * @return 子菜单数据
     */
    private List<CategoryEntity> getChildren(CategoryEntity current, List<CategoryEntity> allData) {
        return allData.stream()
                /*过滤子分类*/
                .filter(c -> c.getParentCid().equals(current.getCatId()))
                /*递归找每一个子分类的子分类*/
                .map(c -> {
                    c.setChildren(this.getChildren(c, allData));
                    return c;
                })
                /*排序*/
                .sorted(Comparator
                        .comparingInt(prev -> (prev.getSort() == null ? 0 : prev.getSort())))
                /*收集*/
                .collect(Collectors.toList());
    }


    @Override
    public void removeCategoryByIds(List<Long> asList) {
        //TODO 删除前引用检查
        
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public void saveCategory(CategoryEntity category) {
        // 初始化分类数据
        category.setShowStatus(1);
        category.setProductCount(0);
        baseMapper.insert(category);
    }

}